package com.hui.admin.common.exception;

import com.hui.admin.common.enums.ErrorCodeEnum;
import com.hui.admin.common.result.Result;
import com.hui.admin.common.result.Results;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常拦截器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理用户自定义业务异常
     */
    @ExceptionHandler(UserException.class)
    public Result<?> handleBusinessException(HttpServletRequest request, UserException ex) {
        logError(request, ex);
        return Results.failure(ex.getErrorCode(), ex.getMessage());
    }

    /**
     * 处理公告自定义业务异常
     */
    @ExceptionHandler(AnnouncementException.class)
    public Result<?> handleBusinessException(HttpServletRequest request, AnnouncementException ex) {
        logError(request, ex);
        return Results.failure(ex.getErrorCode(), ex.getMessage());
    }

    /**
     * 处理请求参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleValidationExceptions(HttpServletRequest request, MethodArgumentNotValidException ex) {
        logError(request, ex);
        String errorMessage = ex.getBindingResult().getAllErrors().getFirst().getDefaultMessage();
        return Results.failure(ErrorCodeEnum.INVALID_PARAMS.getCode(), errorMessage);
    }

    /**
     * 打印异常日志
     */
    private void logError(HttpServletRequest request, Exception ex) {
        log.error(
                "[{}] {} [ex: {}] {}",
                request.getMethod(),
                request.getRequestURL().toString(),
                ex.getClass().getSimpleName(),
                ex.getMessage()
        );
    }
}
